//
//  SafeListViewController.m
//  Estate
//
//  Created by wangdongdong on 2017/9/27.
//  Copyright © 2017年 ttsx. All rights reserved.
//

#define DIC_EXPANDED @"expanded" //是否是展开 0收缩 1展开
#define DIC_ARARRY @"array"
#define DIC_TITILESTRING @"title"
#define CELL_HEIGHT 46.0f

#import "SafeViewController.h"
#import "SafeDetailViewController.h"
#import "addView.h"
#import "SecurityRecordBasic.h"
#import "SafeListCell.h"
#import "SafeListViewController.h"
#import "TTZhuanJianRightView.h"


@interface SafeListViewController ()<UITableViewDelegate, UITableViewDataSource, UIGestureRecognizerDelegate,UICollectionViewDelegate>

//侧边栏/
@property (strong ,nonatomic)TTZhuanJianRightView *rightView;
//所有监理员
@property (nonatomic,copy) NSMutableArray *jianliArr;
//选中监理员
@property (nonatomic,copy) NSMutableArray *jianliArrSelect;
@property (nonatomic,assign) BOOL isz;


// 表格
@property (strong, nonatomic) UITableView *tableView;
// 数据源
@property (strong, nonatomic) NSMutableArray *dataArray;
// 添加视图
@property (strong, nonatomic) addView *aView;

@end

@implementation SafeListViewController


- (UITableView *)tableView {
    if(_tableView==nil){
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, DEF_SCREEN_HEIGHT-64-49-55)];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
        [_tableView registerNib:[UINib nibWithNibName:@"SafeListCell" bundle:nil] forCellReuseIdentifier:@"safeListCell"];
    }
    return _tableView;
}

// 数据源
- (NSMutableArray *)dataArray {
    if(_dataArray==nil){
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

// 添加视图
- (addView *)aView {
    if (!_aView) {
        _aView = [[addView alloc] initWithFrame:CGRectMake(DEF_SCREEN_WIDTH, 0, DEF_SCREEN_WIDTH, DEF_SCREEN_HEIGHT)];
        _aView.addArr = @[@[@"施工三类人员核查", @"特种作业人员持证情况", @"监理安全巡查", @"危险性较大工程监理检查", @"施工设备进场验收监理核查"]];
        
        _aView.VCArr = @[@[@"SafeViewController"]];
        _aView.navVC = self.navigationController;
        _aView.typeStr = @"安全";
        
        // 点击事件
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(disappear)];
        tapGesture.delegate = self;
        [self.aView addGestureRecognizer:tapGesture];
    }
    return _aView;
}

// 蒙版消失
- (void)disappear {
    [UIView animateWithDuration:0.5 animations:^{
        self.aView.frame = CGRectMake(DEF_SCREEN_WIDTH, 0, DEF_SCREEN_WIDTH, DEF_SCREEN_HEIGHT);
    }];
}

-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    // 如果当前是tableView, 做自己想做的事
    if ([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"]) {
        return NO;
    }
    return YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithRed:0.97 green:0.97 blue:0.97 alpha:1.00];
    [self.view addSubview:self.tableView];

    // 创建添加btn
    UIButton *addBtn = [[UIButton alloc] initWithFrame:CGRECTS(260, 360, 100, 100)];
    [self.view addSubview:addBtn];
    [addBtn setImage:[UIImage imageNamed:@"add_2"] forState:UIControlStateNormal];
    [addBtn addTarget:self action:@selector(addContent) forControlEvents:UIControlEventTouchUpInside];
    
    // 添加通知
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(initDataSource) name:@"Refresh_jl_jl" object:nil];
    // 刷新列表页
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(initDataSource) name:@"refreshSafeList" object:nil];
    
    NSString *role = DEF_PERSISTENT_GET_OBJECT(@"role");
    // 专业监理员
    if ([role isEqualToString:@"USER_07"]) {
        self.jianliArr = [LSUtility queryByType:@"USER_03"];
        self.jianliArrSelect = self.jianliArr;
        self.isz = YES;
        [self addShaixuanBtn];
        dispatch_async(dispatch_get_main_queue(), ^{
            UIWindow *myWindow=[UIApplication sharedApplication].keyWindow;
            [myWindow addSubview:self.listView];
        });
    }
    // 查找数据
    [self initDataSource];
}
-(NSString *)getUserIDWithArray:(NSMutableArray *)arr{
    if (self.isz) {
        NSString *str = [NSString stringWithFormat:@"\'%@\'",USERID];
        for (NSDictionary *dic in arr) {
            NSString *userid = dic[@"userid"];
            str=[str stringByAppendingString:[NSString stringWithFormat:@",\'%@\'",userid]];
        }
        return str;

    }else{
        NSString *str = @"";
        for (NSDictionary *dic in arr) {
            NSString *userid = dic[@"userid"];
            if ([str isEqualToString:@""]) {
                str = [NSString stringWithFormat:@"\'%@\'",userid];
            }else{
                str=[str stringByAppendingString:[NSString stringWithFormat:@",\'%@\'",userid]];
            }
        }
        return str;
    }
    
}
//懒加载
-(TTZhuanJianRightView *)listView{
    if(_rightView==nil){
        _rightView=[[TTZhuanJianRightView alloc]initWithFrame:CGRectMake(DEF_SCREEN_WIDTH,0,DEF_SCREEN_WIDTH, DEF_SCREEN_HEIGHT) dataArr:self.jianliArr];
        WEAKSELF
        _rightView.clickOkBtnBlock = ^(NSMutableArray *seleceArr) {
            if (seleceArr.count>0) {
                weakSelf.jianliArrSelect = seleceArr;
                weakSelf.isz = NO;
            }else{
                weakSelf.jianliArrSelect = weakSelf.jianliArr;
                weakSelf.isz = YES;
            }
            [weakSelf initDataSource];
            [weakSelf.tableView reloadData];
        };
    }
    return _rightView;
}
-(void)addShaixuanBtn{
    //弹出选择人物视图
    UIButton *rightBtn=[[UIButton alloc]initWithFrame:CGRECTS(DEF_SCREEN_WIDTH-70, 30, 70, 30)];
    rightBtn.tag=101;
    rightBtn.backgroundColor=[UIColor colorWithRed:0.78 green:0.26 blue:0.09 alpha:1.00];
    [rightBtn setTitle:@"人员选择" forState:UIControlStateNormal];
    rightBtn.titleLabel.font=[UIFont systemFontOfSize:13.];
    [rightBtn addTarget:self action:@selector(rightBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:rightBtn];
}
#pragma mark-添加按钮
- (void)rightBtnClick:(UIButton *)sender{
    
    [UIView animateWithDuration:0.4 animations:^{
        _rightView.frame =CGRectMake(0, 0, DEF_SCREEN_WIDTH, DEF_HEIGHT(self.view));
    }];
}

#pragma  mark-添加安全
- (void)addContent {
    [UIView animateWithDuration:0.5 animations:^{
        self.aView.frame = CGRectMake(0, 0, DEF_SCREEN_WIDTH, DEF_SCREEN_HEIGHT);
    }];
}

- (void)viewWillAppear:(BOOL)animated {
    //添加视图
    [[UIApplication sharedApplication].keyWindow addSubview:self.aView];
}
// 查找数据
- (void)initDataSource
{
    // 清空数据源
    [self.dataArray removeAllObjects];
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    FMResultSet *result;
    NSString *role = DEF_PERSISTENT_GET_OBJECT(@"role");
    // 监理
    if ([role isEqualToString:@"USER_03"]) {
        NSLog(@"监理 %@",SQL_SAFE_LIST_JL(PROID, USERID));
        result = [db executeQuery:SQL_SAFE_LIST_JL(PROID, USERID)];
    //专监
    }else if([role isEqualToString:@"USER_07"]){
        NSString *userids = [self getUserIDWithArray:self.jianliArrSelect];
        NSString *sql = [NSString stringWithFormat:@"SELECT COUNT(*), date(CREATE_TIME), substr(CREATE_TIME, 1, 4) as year, substr(CREATE_TIME, 6, 2) as month, substr(CREATE_TIME, 9, 2) as day, * FROM SAFE_RECORD_BASIC WHERE PRO_ID = '%@' AND RECORD_USER in(%@) GROUP BY date(CREATE_TIME) ORDER BY date(CREATE_TIME) desc", PROID, userids];
        result = [db executeQuery:sql];

    // 总监
    } else {
        NSLog(@"总监 %@",SQL_SAFE_LIST_ZJ(PROID, USERID));
        result = [db executeQuery:SQL_SAFE_LIST_ZJ(PROID, USERID)];
    }
    NSMutableDictionary *dic;
    while ([result next]) {
        // 查询条件
        NSString *time = [result stringForColumn:@"date(CREATE_TIME)"];
        // 查询到年
        NSString *year = [result stringForColumn:@"year"];
        // 查询到月
        NSString *month = [LSUtility deletaeZero:[result stringForColumn:@"month"]];
        // 查询到日
        NSString *day = [LSUtility deletaeZero:[result stringForColumn:@"day"]];
        // 根据日期查询展开的数据
        NSString *sqlStr;
        NSString *role = DEF_PERSISTENT_GET_OBJECT(@"role");
        // 监理
        if ([role isEqualToString:@"USER_03"]) {
            sqlStr = [NSString stringWithFormat:@"SELECT *, time(CREATE_TIME) FROM SAFE_RECORD_BASIC WHERE PRO_ID = '%@' AND RECORD_USER = '%@' AND date(CREATE_TIME) ='%@' ORDER BY CREATE_TIME desc", PROID, USERID, time];
        }else if([role isEqualToString:@"USER_07"]){
            NSString *userids = [self getUserIDWithArray:self.jianliArrSelect];
            sqlStr = [NSString stringWithFormat:@"SELECT *, time(CREATE_TIME) FROM SAFE_RECORD_BASIC WHERE PRO_ID = '%@' AND RECORD_USER in(%@) AND date(CREATE_TIME) ='%@' ORDER BY CREATE_TIME desc", PROID, userids, time];
            // 总监
        } else if ([role isEqualToString:@"USER_01"]) {
            sqlStr = [NSString stringWithFormat:@"SELECT * ,time(CREATE_TIME) FROM SAFE_RECORD_BASIC WHERE PRO_ID = '%@' AND (RECORD_USER = '%@' OR STATE = '1') AND date(CREATE_TIME) ='%@' ORDER BY CREATE_TIME desc ", PROID, USERID, time];
        }
        
        FMResultSet *results = [db executeQuery:sqlStr];
        // 查询到记录
        NSMutableArray *DetailArr = [NSMutableArray array];
        while ([results next]) {
            SecurityRecordBasic *model = [[SecurityRecordBasic alloc]init];
            model.id = [results stringForColumn:@"ID"];
            model.proId = [results stringForColumn:@"PRO_ID"];
            model.supervisorProUnitId = [results stringForColumn:@"SUPERVISOR_PRO_UNIT_ID"];
            model.constructProUnitId = [results stringForColumn:@"CONSTRUCT_PRO_UNIT_ID"];
            model.supervisorProUnitName = [results stringForColumn:@"SUPERVISOR_PRO_UNIT_NAME"];
            model.constructProUnitName = [results stringForColumn:@"CONSTRUCT_PRO_UNIT_NAME"];
            model.supervisorContractNumber = [results stringForColumn:@"SUPERVISOR_CONTRACT_NUMBER"];
            model.constructContractNumber = [results stringForColumn:@"CONSTRUCT_CONTRACT_NUMBER"];
            model.recordUser = [results stringForColumn:@"RECORD_USER"];
            model.recordType = [results stringForColumn:@"RECORD_TYPE"];
            model.recordTitle = [results stringForColumn:@"RECORD_TITLE"];
            model.recordContent = [results stringForColumn:@"RECORD_CONTENT"];
            model.state = [results stringForColumn:@"STATE"];
            model.recordNumber = [results stringForColumn:@"RECORD_NUMBER"];
            model.supervisorOpinion = [results stringForColumn:@"SUPERVISOR_OPINION"];
            model.chiefSupervisorOpinion = [results stringForColumn:@"CHIEF_SUPERVISOR_OPINION"];
            model.projectContent = [results stringForColumn:@"PROJECT_CONTENT"];
            model.otherInfo = [results stringForColumn:@"OTHER_INFO"];
            model.weather = [results stringForColumn:@"WEATHER"];
            model.addId = [results stringForColumn:@"ADD_ID"];
            model.addInfo = [results stringForColumn:@"ADD_INFO"];
            model.extendInfo = [results stringForColumn:@"EXTEND_INFO"];
            model.createusername = [results stringForColumn:@"CREATE_USER_NAME"];
            model.createtime = [results stringForColumn:@"CREATE_TIME"];
            model.createip = [results stringForColumn:@"CREATE_IP"];
            model.modifyusername = [results stringForColumn:@"MODIFY_USER_NAME"];
            model.modifytime = [results stringForColumn:@"MODIFY_TIME"];
            model.modifyip = [results stringForColumn:@"MODIFY_IP"];
            model.constructContractMoney = [results stringForColumn:@"CONSTRUCT_CONTRACT_MONEY"];
            model.recifyState = [results stringForColumn:@"RECIFY_STATE"];
            model.localState = [results stringForColumn:@"LOCAL_MODIFY_STATE"];
    
            [DetailArr addObject:model];
        }
        // 查询到数量
        NSString *counts = [result stringForColumn:@"COUNT(*)"];
        // 拼接成标题
        NSString *tiemAndCount = [NSString stringWithFormat:@"%@年%@月%@日 (%@条)",year,month,day,counts];
        //创建一个字典 包含数组，分组名，是否展开的标示
        dic = [[NSMutableDictionary alloc] initWithObjectsAndKeys:DetailArr, DIC_ARARRY, tiemAndCount, DIC_TITILESTRING, [NSNumber numberWithInt:0], DIC_EXPANDED, nil];
        //将字典加入数组
        [self.dataArray addObject:dic];
    }
    [db close];
    [self.tableView reloadData];
}

#pragma mark - UITableViewDelegate, UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataArray.count;
}

// 控制表头分组表头高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 44*BIZ;
}

//设置分组头的视图
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *hView = [[UIView alloc]initWithFrame:CGRectMake(0,0, DEF_SCREEN_WIDTH, CELL_HEIGHT-10)];
    hView.backgroundColor=[UIColor colorWithRed:0.94 green:0.94 blue:0.94 alpha:1.00];
    UIButton* eButton = [[UIButton alloc] init];
    eButton.backgroundColor=[UIColor whiteColor];
    //按钮填充整个视图
    eButton.frame = hView.frame;
    [eButton addTarget:self action:@selector(expandButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    //把节号保存到按钮tag，以便传递到expandButtonClicked方法
    eButton.tag = section;
    //根据是否展开，切换按钮显示图片
    if ([self isExpanded:section])
        [eButton setImage:  [UIImage imageNamed: @"xiala" ]forState:UIControlStateNormal];
    else
        [eButton setImage: [UIImage imageNamed: @"gengduo1" ]forState:UIControlStateNormal];
    
    //设置分组标题
    [eButton setTitle:[[self.dataArray objectAtIndex:section] objectForKey:DIC_TITILESTRING]forState:UIControlStateNormal];
    
    [eButton setTitleColor:[UIColor colorWithRed:0.68 green:0.68 blue:0.68 alpha:1.00] forState:UIControlStateNormal];
    //设置字体样式
    eButton.titleLabel.font=[UIFont systemFontOfSize:16.*BIZ];
    
    //设置button的图片和标题的相对位置
    eButton.contentHorizontalAlignment =UIControlContentHorizontalAlignmentLeft;
    [eButton setTitleEdgeInsets:UIEdgeInsetsMake(0,5, 0,0)];
    [eButton setImageEdgeInsets:UIEdgeInsetsMake(0,DEF_SCREEN_WIDTH-30, 0,0)];
    
    //添加btn
    [hView addSubview: eButton];
    return hView;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSMutableDictionary *dic = [self.dataArray objectAtIndex:section];
    NSArray *array = [dic objectForKey:DIC_ARARRY];
    //判断是收缩还是展开
    if ([[dic objectForKey:DIC_EXPANDED]intValue]) {
        return array.count;
        
    }else{
        return 0;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 70*BIZ;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    long section = indexPath.section;
    long row = indexPath.row;
    // 得到改组下信息
    NSMutableDictionary *dic = [self.dataArray objectAtIndex:section];
    NSArray *array = [dic objectForKey:DIC_ARARRY];
    SecurityRecordBasic *model = array[row];
    
    SafeListCell *listCell = [tableView dequeueReusableCellWithIdentifier:@"safeListCell" forIndexPath:indexPath];
    listCell.selectionStyle = NO;
    
    /**审阅状态*/
    // 监理安全巡查
    if ([model.recordType isEqualToString:@"SAFE_RECORD_01"]) {
        listCell.reviewStatusLabel.text = @"已审阅";
    // 其他
    } else {
        // 未审阅
        if ([model.recifyState isEqualToString:@"0"]) {
            listCell.reviewStatusLabel.textColor = [UIColor colorWithRed:0.08 green:0.61 blue:0.56 alpha:1.00];
            listCell.reviewStatusLabel.text = @"未审阅";
            // 已审阅
        } else if ([model.recifyState isEqualToString:@"1"]) {
            listCell.reviewStatusLabel.textColor = [UIColor colorWithRed:0.34 green:0.45 blue:0.65 alpha:1.00];
            listCell.reviewStatusLabel.text = @"已审阅";
        }
    }

    // 安全施工三类人员
    if ([model.recordType isEqualToString:@"SAFE_RECORD_02"]) {
        listCell.identificationImageView.image = [UIImage imageNamed:@"threeConstruction"];
    // 特种作业人员持证情况
    } else if ([model.recordType isEqualToString:@"SAFE_RECORD_04"]) {
        listCell.identificationImageView.image = [UIImage imageNamed:@"specialOperations"];
    // 监理安全巡查
    } else if ([model.recordType isEqualToString:@"SAFE_RECORD_01"]) {
        listCell.identificationImageView.image = [UIImage imageNamed:@"JLSafe"];
    // 危险性较大工程监理检查
    } else if ([model.recordType isEqualToString:@"SAFE_RECORD_03"]) {
        listCell.identificationImageView.image = [UIImage imageNamed:@"danger"];
    // 施工设备进场验收监理核查
    } else if ([model.recordType isEqualToString:@"SAFE_RECORD_05"]) {
        listCell.identificationImageView.image = [UIImage imageNamed:@"construction"];
    }
    // 标题
    listCell.titleLabel.text = model.recordTitle;
    // 姓名
    listCell.peopleLabel.text = [LSUtility getuserIdByUserName:model.recordUser][@"REAL_NAME"];
    // 位置
    NSDictionary *exDic=[LSUtility dictionaryWithJsonString:model.addInfo];
    listCell.areaLabel.text = [NSString stringWithFormat:@"%@ %@",DEFISNUL(exDic[@"address"]),DEFISNUL(exDic[@"leftDistanceStr"])];

    // 时间
    listCell.timeLabel.text = [model.createtime substringFromIndex:11];
    // 状态
    if ([model.localState isEqualToString:@"ADD"] || [model.localState isEqualToString:@"MOD"]) {
        listCell.stateImage.image = [UIImage imageNamed:@"tishi"];
    } else {
        listCell.stateImage.image = [UIImage imageNamed:@""];
    }
    [model.createtime substringFromIndex:11];
    return listCell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    //判断是收缩还是展开
    NSMutableDictionary *dic = [self.dataArray objectAtIndex:section];
    if ([[dic objectForKey:DIC_EXPANDED]intValue]) {
        return 5;
        
    } else {
        return 0;
    }
}

#pragma mark-点击表格
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //得到改组下信息
    NSMutableDictionary *dic=[self.dataArray objectAtIndex:indexPath.section];
    NSArray *array=[dic objectForKey:DIC_ARARRY];
    SecurityRecordBasic *model = array[indexPath.row];
    SafeDetailViewController *safeDetailVC = [[SafeDetailViewController alloc] init];
    safeDetailVC.safeModel = model;
    [self.navigationController pushViewController:safeDetailVC animated:YES];
}

#pragma mark -- 内部调用
// 对指定的节进行“展开/折叠”操作,若原来是折叠的则展开，若原来是展开的则折叠
-(void)collapseOrExpand:(long)section{
    NSMutableDictionary *dic=[self.dataArray objectAtIndex:section];
    int expanded=[[dic objectForKey:DIC_EXPANDED] intValue];
    if (expanded) {
        [dic setValue:[NSNumber numberWithInt:0]forKey:DIC_EXPANDED];
        
    } else {
        [dic setValue:[NSNumber numberWithInt:1]forKey:DIC_EXPANDED];
    }
}

// 返回指定节是否是展开的
- (int)isExpanded:(long)section {
    NSDictionary *dic = [self.dataArray objectAtIndex:section];
    int expanded=[[dic objectForKey:DIC_EXPANDED] intValue];
    return expanded;
}

// 按钮被点击时触发
- (void)expandButtonClicked:(id)sender {
    UIButton* btn = (UIButton*)sender;
    long section = btn.tag;//取得tag知道点击对应哪个块
    [self collapseOrExpand:section];
    //刷新tableview
    [self.tableView reloadData];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)didReceiveMemoryWarning{
    DeLog(@"内存警告");
}



@end


